package com.teame.readbaby;

import java.util.Map;

import org.json.JSONException;

import com.teame.readbaby.net.HttpClientAdapter;
import com.teame.readbaby.parser.BaseParser;
import com.teame.readbaby.util.CommonUtil;
import com.teame.readbaby.util.ConstantValue;
import com.teame.readbaby.util.GloableParams;
import com.teame.readbaby.util.Logger;
import com.teame.readbaby.util.NetUtil;
import com.teame.readbaby.util.ThreadPoolManager;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable.ConstantState;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.SyncStateContract.Constants;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public abstract class BaseActivity extends Activity implements
		View.OnClickListener {
	public static final String TAG = "BaseActivity";
	protected int activityCase;
	private ImageView classify;//
	private ImageView home;
	private ImageView more;
	protected ProgressDialog progressDialog;// dpt:进度条对话框
	private ImageView search;
	private ImageView shopCar;
	protected TextView textShopCarNum;
	protected Context context;
	private ThreadPoolManager threadPoolManager;// dpt:管理线程池的类

	public BaseActivity() {
		threadPoolManager = ThreadPoolManager.getInstance();
	}

	/**
	 * 
	 */
	@Override
	public void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		// getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
		// WindowManager.LayoutParams.FLAG_FULLSCREEN);
		context = getApplicationContext();
		initView();
	}
	
	/**
	 * 
	 */
	private void initView() {
		loadViewLayout();
		if (isLoadBottomTab()) {// 是否加载底部的tab
			loadBottomTab();
			selectedBottomTab(GloableParams.defaultIndex);
			Logger.i(TAG, "加载底部的tab");
		}
		findViewById();
		setListener();
		processLogic();
		// 初始化底部导航
		// initDH();
		// // 菜单
		// initMenu();
	}

	/**
	 * 初始化底部导航
	 */
	public void initMenu() {

	}

	/**
	 * 菜单
	 */
	private void initDH() {

	}

	/**
	 * 显示进度条
	 * 
	 */
	protected void showProgressDialog() {
		// dpt:If the activity is finishing, returns true; else returns false
		if ((!isFinishing()) && (this.progressDialog == null)) {
			this.progressDialog = new ProgressDialog(this);
		}
		this.progressDialog.setTitle(ConstantValue.LOADTITLE);
		this.progressDialog.setMessage(ConstantValue.LOADCONTENT);
		this.progressDialog.show();
	}

	/**
	 * 关闭进度条对话框
	 */
	protected void closeProgressDialog() {
		if (this.progressDialog != null)
			this.progressDialog.dismiss();
	}

	/**
	 * 子类在这个方法中设置点击事件
	 * 
	 * @param paramView
	 */
	protected abstract void onClickEvent(View paramView);

	/**
	 * 你懂的
	 */
	protected abstract void findViewById();

	/**
	 * 加载布局文件
	 */
	protected abstract void loadViewLayout();

	/**
	 * 向本地请求数据
	 */
	protected abstract void processLogic();

	/**
	 * 设置事件
	 */
	protected abstract void setListener();

	/**
	 * 从服务器上获取数据，并回调处理
	 * 
	 * @param reqVo
	 *            向服务发送请求得封装类
	 * @param callBack
	 *            回调函数
	 * @param baseParser
	 *            具体的解析器
	 */
	protected void getDataFromServer(String url, Map<String, String> params,
			BaseParser baseParser, DataCallback callBack) {
		showProgressDialog();
		BaseHandler handler = new BaseHandler(this, callBack);
		BaseTask taskThread = new BaseTask(this, url, params, baseParser,
				handler);
		this.threadPoolManager.addTask(taskThread);
	}

	public abstract interface DataCallback<T> {
		public abstract void processData(T paramObject, boolean paramBoolean);
	}

	
	/**
	 * 用来执行回调函数
	 * 
	 * @author dupengtao
	 */
	@SuppressWarnings("unchecked")
	class BaseHandler extends Handler {
		private Context context;
		private DataCallback callBack;

		public BaseHandler(Context context, DataCallback callBack) {
			this.context = context;
			this.callBack = callBack;
		}

		@Override
		public void handleMessage(Message msg) {
			closeProgressDialog();
			if (msg.what == ConstantValue.MSG_SUCCESS) {
				callBack.processData(msg.obj, true);
				/*只要parse出错了就提示网络异常不科学,大家还是在自己的processData方法里处理null吧
				if (msg.obj == null) {
					CommonUtil.showInfoDialog(context, ConstantValue.NET_ERROR);
				} else {
					// dpt:执行回调函数
					callBack.processData(msg.obj, true);
				}
				*/
			} else if (msg.what == ConstantValue.MSG_NET_FAILED) {
				// dpt:执行回调函数
				// callBack.processData(null, false);
				CommonUtil.showInfoDialog(context, ConstantValue.NET_ERROR);
			} else if (msg.what == ConstantValue.MSG_FAILURE) {
				// dpt:执行回调函数
				// callBack.processData(null, false);
				CommonUtil.showInfoDialog(context, ConstantValue.JSON_ERROR);
			}
		}
	}

	class BaseTask implements Runnable {
		private Context context;
		private Handler handler;
		private HttpClientAdapter adapter;
		private BaseParser baseParser;
		private String url;// 请求地址
		private Map<String, String> params;// 请求参数

		/**
		 * dpt
		 * 
		 * @param context
		 *            你懂的
		 * @param url
		 *            请求地址
		 * @param params
		 *            请求参数，如果没有为null
		 * @param baseParser
		 *            获取后json的解析器
		 * @param handler
		 *            你懂的
		 */
		public BaseTask(Context context, String url,
				Map<String, String> params, BaseParser baseParser,
				Handler handler) {
			this.context = context;
			this.handler = handler;
			this.baseParser = baseParser;
			this.url = url;
			this.params = params;

			adapter = new HttpClientAdapter();
		}

		@Override
		public void run() {
			Object obj = null;
			Message msg = new Message();
			// dpt:检查网络连接状态
			if (NetUtil.checkNet(context)) {
				// dpt:获取json
				String sJson = adapter.sendPost(url, params);
				// dpt:封装成vo
				Object valueObject = null;
				try {
					valueObject = baseParser.parseJSON(sJson);
				} catch (JSONException e) {
					e.printStackTrace();
					msg.what = ConstantValue.MSG_FAILURE;
					msg.obj = obj;
					handler.sendMessage(msg);
				}

				msg.what = ConstantValue.MSG_SUCCESS;
				msg.obj = valueObject;
				handler.sendMessage(msg);
			} else {
				msg.what = ConstantValue.MSG_NET_FAILED;
				msg.obj = obj;
				handler.sendMessage(msg);
			}
		}

	}

	@Override
	public void onClick(View paramView) {
		Logger.i(TAG, "相应了父类点击事件");
		// onClickBottmBarEvent(paramView);
		if (!onClickBottmBarEvent(paramView))
			onClickEvent(paramView);
	}

	/**
	 * 
	 * 
	 * @param paramView
	 * @return
	 */
	private boolean onClickBottmBarEvent(View paramView) {
		boolean isBar = true;
		Intent intent = new Intent();
		switch (paramView.getId()) {
		case R.id.imgHome:
			// selectedBottomTab(1);
			// intent.setClass(this, HomeActivity.class);
			// intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);//reorder
			// to front
			// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			// startActivity(intent);
			
			if(GloableParams.defaultIndex!=1){
				intent = new Intent(this, HomeActivity.class);
				startActivity(intent);
			}	
			selectedBottomTab(1);
			
//			Toast.makeText(this, "跳转到主界面", 0).show();
			Logger.i(TAG, "跳转到主界面");



			break;
		case R.id.imgClassify:
			// selectedBottomTab(2);
			// intent.setClass(this, CategoryActivity.class);
			// startActivity(intent);
			
			if(GloableParams.defaultIndex!=2){
//				intent.setClass(this, MoreActivity.class);
//				startActivity(intent);
			}	
			selectedBottomTab(2);
			
			Toast.makeText(this, "跳转到分类界面", 0).show();
			break;
		case R.id.imgSearch:
			// selectedBottomTab(3);
			// intent.setClass(this, SearchActivity.class);
			// startActivity(intent);
			
			if(GloableParams.defaultIndex!=3){
				intent.setClass(this, SearchActivityFake.class);
				startActivity(intent);
			}	
			selectedBottomTab(3);
			//Toast.makeText(this, "跳转到搜索界面", 0).show();
//			intent = new Intent(this, SearchActivity.class);
//			startActivity(intent);
			break;
		case R.id.imgShoppingCar:
			// selectedBottomTab(4);
			
			if(GloableParams.defaultIndex!=4){
				intent.setClass(this, ShoppingCartActivity2.class);
				startActivity(intent);
			}	
			selectedBottomTab(4);
			
			Toast.makeText(this, "跳转到购物车界面", 0).show();
			break;
		case R.id.imgMore:
			
			if(GloableParams.defaultIndex!=5){
				intent.setClass(this, MoreActivity.class);
				startActivity(intent);
			}	
			selectedBottomTab(5);
			// Toast.makeText(this, "跳转到更多界面", 0).show();
			break;
		default:
			isBar = false;
			break;
		}
		return isBar;
	}

	private void loadBottomTab() {
		this.home = (ImageView) findViewById(R.id.imgHome);
		this.classify = (ImageView) findViewById(R.id.imgClassify);
		this.search = (ImageView) findViewById(R.id.imgSearch);
		this.shopCar = (ImageView) findViewById(R.id.imgShoppingCar);
		this.more = (ImageView) findViewById(R.id.imgMore);
		this.textShopCarNum = (TextView) findViewById(R.id.textShopCarNum);
		this.home.setOnClickListener(this);
		this.classify.setOnClickListener(this);
		this.search.setOnClickListener(this);
		this.shopCar.setOnClickListener(this);
		this.more.setOnClickListener(this);
	}

	/**
	 * tab条图片切换
	 * 
	 * @param paramViewId
	 */
	protected boolean selectedBottomTab(int paramViewId) {

		// if(GloableParams.defaultIndex==paramViewId){
		// return false;
		// }

		this.home.setBackgroundResource(R.drawable.bar_home_normal);
		this.classify.setBackgroundResource(R.drawable.bar_class_normal);
		this.search.setBackgroundResource(R.drawable.bar_search_normal);
		this.shopCar.setBackgroundResource(R.drawable.bar_shopping_normal);
		this.more.setBackgroundResource(R.drawable.bar_more_normal);
		switch (paramViewId) {
		case ConstantValue._HOME:
			this.home.setBackgroundResource(R.drawable.bar_home_selected);
			GloableParams.defaultIndex = ConstantValue._HOME;
			break;
		case ConstantValue._CLASSIFY:
			this.classify.setBackgroundResource(R.drawable.bar_class_selected);
			GloableParams.defaultIndex = ConstantValue._CLASSIFY;
			break;
		case ConstantValue._SEARCH:
			this.search.setBackgroundResource(R.drawable.bar_search_selected);
			GloableParams.defaultIndex = ConstantValue._SEARCH;
			break;
		case ConstantValue._SHOPCAR:
			this.shopCar
					.setBackgroundResource(R.drawable.bar_shopping_selected);
			GloableParams.defaultIndex = ConstantValue._SHOPCAR;
			break;
		case ConstantValue._MORE:
			this.more.setBackgroundResource(R.drawable.bar_more_selected);
			GloableParams.defaultIndex = ConstantValue._MORE;
			break;
		}
		return true;
	}

	/**
	 * 是否加载底部tab 如何有的界面没有底部导航就覆写这个方法 返回值 变成false
	 * 
	 * @return
	 */
	protected Boolean isLoadBottomTab() {
		return true;
	}

}
